package jmine.tec.persist.hibernate.merger;

import java.io.Serializable;

import bancosys.tec.persist.Persistable;
import bancosys.tec.persist.dao.BaseDAO;
import bancosys.tec.persist.dao.BaseDAOFactory;
import bancosys.tec.persist.dao.BeanNotFoundException;

/**
 * EntityLoader que atua através de DAOs.
 * 
 * @author lundberg
 */
public class DAOEntityLoader implements EntityLoader {

    private BaseDAOFactory daoFactory;

    /**
     * {@inheritDoc}
     */
    public <T> T get(Class<T> entityClass, Serializable id) {
        try {
            return entityClass.cast(this.getDAO(entityClass.asSubclass(Persistable.class)).findByPk(id));
        } catch (BeanNotFoundException e) {
            return this.create(entityClass);
        }
    }

    /**
     * {@inheritDoc}
     */
    public <T> T create(Class<T> entityClass) {
        return entityClass.cast(this.getDAO(entityClass.asSubclass(Persistable.class)).createBean());
    }

    /**
     * Obtém o dao para a entidade
     * 
     * @param <T> tipo da entidade
     * @param entityClass entityClass
     * @return dao
     */
    private <T extends Persistable> BaseDAO<T> getDAO(Class<T> entityClass) {
        return this.daoFactory.getGenericDAO(entityClass);
    }

    /**
     * @param daoFactory the daoFactory to set
     */
    public void setDaoFactory(BaseDAOFactory daoFactory) {
        this.daoFactory = daoFactory;
    }

}
